/*
 * @Author: yangzonglong
 * @Date: 2021-05-12 14:36:18
 * @version: v1.0.0
 * @Descripttion: 角色
 * @LastEditors: yangzonglong
 * @LastEditTime: 2021-05-21 14:00:10
 * @Auditor: 
 */
import React, { useMemo, useState, useRef, useCallback } from 'react';
import { Table, PageHeader, Button, units, ActionText } from '@library';
import { Modal } from 'antd';
import { TableRefProps } from '@library/components/table/interface';
import { addRoles, delRole } from '../Api';

const bodyStyle: React.CSSProperties = { 
  height: '500px',
  display: 'flex',
  flexDirection: 'column'
};

const action = { dataIndex: 'action', width: 100 };
const columns = [{ dataIndex: 'roleName' }];
const T = window.$app.t;

interface RoleProps {
  workflowId: string;
  disabled: boolean
}

export default ({ workflowId, disabled }: RoleProps) => {
  const roleTableRef = useRef<TableRefProps>(null);
  const addTableRef = useRef<TableRefProps>(null);
  const [visible, setVisible] = useState(false);

  const onCancel = useCallback(() => setVisible(false), []);

  const onOk = useCallback(async () => {
    const selectedRows = await addTableRef.current?.getSelectedRows();
    const dataSource = await roleTableRef.current?.getDataSource();

    const map = dataSource?.reduce((next, cur) => {
      next[cur.roleId] = true;
      return next;
    }, {});
    
    const filter = selectedRows?.filter(item => !map[item.id]);
    const result = await addRoles(filter?.map(item => {
      const copyItem = { ...item };
      delete copyItem.id;
      return { 
        ...copyItem, 
        WorkFlowHeadId: workflowId, 
        roleId: item.id 
      }
    }) as any);

    if(result) {
      units.message.success();
      roleTableRef.current?.onRefresh();
      setVisible(false);
    }
  }, [workflowId]);

  const query = useMemo(() => {
    return { where: { WorkFlowHeadId: workflowId } }
  }, [workflowId]);

  const extra = useMemo(() => [
    { dataIndex: 'action', render(text: string, record: Record<string, string>) {
      return <ActionText.Delete onClick={async () => {
        const result = await delRole(record.id);
        if(result) {
          units.message.success();
          roleTableRef.current?.onRefresh();
        }
      }}/>
    }}
  ], []);

  const _columns = useMemo(() => {
    if(disabled) return columns;
    return columns.concat([action]);
  }, [disabled]);

  return (
    <>
      <div className='common-block'>
        <PageHeader title={T('role')} extra={
          !disabled && <Button.Create onClick={() => setVisible(true)}>{T('add')}</Button.Create>
        }/>
        <Table extra={extra} ref={roleTableRef} flat query={query} url='/bk/api/workflow/WorkFlowRole/find' columns={_columns}/>
      </div>
      <Modal onOk={onOk} onCancel={onCancel} width={600} visible={visible} title={T('addRole')} bodyStyle={bodyStyle}>
        <Table ref={addTableRef} rowSelectionType='checkbox' url='/bk/api/company/Role/find' columns={columns}/>
      </Modal>
    </>
  )
}
